/*
 * @lc app=leetcode.cn id=148 lang=javascript
 *
 * [148] 排序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var sortList = function (head) {
  if (!head || !head.next) {
    return head
  }
  let slow = head,
    fast = head
  //快慢指针找到中间节点
  while (fast.next && fast.next.next) {
    slow = slow.next
    fast = fast.next.next
  }

  let mid = slow.next
  let right = mid
  slow.next = null
  let left = head
  return mergeTwoLists(sortList(left), sortList(right))
}
var mergeTwoLists = function (l1, l2) {
  let head = new ListNode()
  let dummy = head

  while (l1 && l2) {
    if (l1.val < l2.val) {
      head.next = l1
      l1 = l1.next
    } else {
      head.next = l2
      l2 = l2.next
    }
    head = head.next
  }
  if (l1) head.next = l1
  if (l2) head.next = l2

  return dummy.next
}
// @lc code=end

// 将链表两两分割，然后合并两个链表
